<script setup lang="ts">
import { computed, defineProps, defineEmits, PropType, ref, watchEffect } from 'vue'
import { getDataItems } from '/@/utils/data'
import { ElRadioGroup } from 'element-plus'
import { omit } from 'lodash-es'

const props = defineProps({
  ...ElRadioGroup.props,
  defaultValue: { type: ElRadioGroup.props.modelValue.type },
  options: { type: Array as PropType<SelectMakerOption[]> },
  dataSource: { type: String },
  hasAll: { type: Boolean, default: false },
})

const emits = defineEmits(['update:modelValue', 'change'])


const propsRaw = computed(() => (omit(props, ['options', 'dataSource'])))
const renderOptions = ref<SelectMakerOption[]>([])

const value = ref('')

const allowRender = ref(false)

const setRenderOptions = (options: SelectMakerOption[]) => {
  if (props.hasAll) {
    options = [{ label: '全部', value: void 0 }, ...options]
  }
  renderOptions.value = options
}

watchEffect(() => {
  if (props.options && props.options.length) {
    setRenderOptions(props.options as SelectMakerOption[])
    allowRender.value = true
  } else if (props.dataSource) {
    getDataItems(props.dataSource).then(items => {
      setRenderOptions(items as SelectMakerOption[])
    }).finally(() => {
      allowRender.value = true
    })
  } else {
    throw new Error(`RadioMaker：options和dataSouece必须有一个不为空！`)
  }
})

watchEffect(() => {
  if ([void 0, '', null].includes(props.modelValue)) {
    const target = renderOptions.value.find(s => s.value === props.defaultValue);
    value.value = target?.label
  } else {
    const target = renderOptions.value.find(s => s.value === props.modelValue);
    value.value = target?.label
  }
})


const handChange = (label: any) => {
  const target = renderOptions.value.find(s => s.label == label)
  emits('update:modelValue', target?.value)
  emits('change', target?.value)
}
</script>

<template>
  <el-radio-group v-model="value" @change="handChange">
    <el-radio-button v-for="item of renderOptions" :key="item.value" :label="item.label"></el-radio-button>
  </el-radio-group>

</template>